﻿using System.Collections;

namespace AMatysiak.Comparers
{
    public class AlphaNumEmptyComparer : IComparer
    {
        private object x;
        private object y;

        private string first;
        private string second;

        private const int BIGGER = 1;
        private const int EQUAL = 0;
        private const int SMALLER = -1;

        public int Compare(object x, object y)
        {
            initializeObjects(x, y);

            if (isOneOfValueNull())
                return EQUAL;

            castToString();

            if (oneOfValueIsEmpty())
                return sortEmptyToAnEnd();

            return compareAlphaNumerically();
        }

        private void initializeObjects(object x, object y)
        {
            this.x = x;
            this.y = y;
        }

        private bool isOneOfValueNull()
        {
            return x == null || y == null;
        }

        private void castToString()
        {
            first = x.ToString();
            second = y.ToString();
        }

        private bool oneOfValueIsEmpty()
        {
            return first == "" || second == "";
        }

        private int sortEmptyToAnEnd()
        {
            if (bothEmpty())
                return EQUAL;

            if (firstEmpty())
                return BIGGER;

            return SMALLER;
        }

        private bool bothEmpty()
        {
            return first == "" && second == "";
        }

        private bool firstEmpty()
        {
            return first == "";
        }

        private int compareAlphaNumerically()
        {
            AlphaNumComparer ac = new AlphaNumComparer();
            return ac.Compare(x, y);
        }
    }
}
